package leetcode.秋招.网易;

/**
 * @author ：zsy
 * @date ：Created 2021/8/21 15:45
 * @description：
 */
public class Main4 {

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.minSailCost(new int[][]{{1, 1, 1, 1, 0}, {0, 1, 0, 1, 0}, {1, 1, 2, 1, 1}, {0, 2, 0, 0, 1}}));
    }

    static class Solution {
        /**
         * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
         *
         * 计算最小航行费用
         * @param input int整型二维数组 二维网格
         * @return int整型
         */
        public int minSailCost (int[][] input) {
            // write code here
            if (input == null || input.length == 0 || input[0].length == 0) return -1;
            int rows = input.length;
            int cols = input[0].length;
            int[][] cashes = new int[rows][cols];
            for (int i = 0; i < rows; i++) {
                for (int j = 0; j < cols; j++) {
                    if (input[i][j] == 2) {
                        cashes[i][j] = Integer.MAX_VALUE;
                        continue;
                    }
                    if (i == 0 && j == 0) continue;
                    if (i == 0) {
                        if (cashes[i][j - 1] == Integer.MAX_VALUE) {
                            cashes[i][j] = Integer.MAX_VALUE;
                        } else {
                            cashes[i][j] = cashes[i][j - 1] + (input[i][j] == 0 ? 2 : 1);
                        }
                    } else if (j == 0) {
                        if (cashes[i - 1][j] == Integer.MAX_VALUE) {
                            cashes[i][j] = Integer.MAX_VALUE;
                        } else {
                            cashes[i][j] = cashes[i - 1][j] + (input[i][j] == 0 ? 2 : 1);
                        }
                    } else {
                        int min = Math.min(cashes[i - 1][j], cashes[i][j - 1]);
                        if (min == Integer.MAX_VALUE) {
                            cashes[i][j] = min;
                        } else {
                            cashes[i][j] = min + (input[i][j] == 0 ? 2 : 1);
                        }
                    }
                }
            }
            return cashes[rows - 1][cols - 1] == Integer.MAX_VALUE ? -1 : cashes[rows - 1][cols - 1];
        }
    }
}


